package com.sudoku.solver;

import java.util.ArrayList;

import com.sudoku.board.Board;
import com.sudoku.board.Tile;

public class UniquePencilCandidate extends Strategy{

	public UniquePencilCandidate(Solver solver) {
		super(solver);
	}

	@Override
	public boolean solve(Board board) {
		stuck=true;
		/*
		 * Unique pencil candidates in rows and cols and boxes
		 */
		// rows
		for (int i = 0; i < 9; i++) {
			if (uniquePencilCandidate(board.getTilesInRow(i))) {
				stuck = false;
			}
		}
		// cols
		for (int i = 0; i < 9; i++) {
			if (uniquePencilCandidate(board.getTilesInCol(i))) {
				stuck = false;
			}
		}
		// box
		for (int i = 0; i < 9; i++) {
			if (uniquePencilCandidate(board.getData().get(i).getData())) {
				stuck = false;
			}
		}
		return stuck;
	}

	/**
	 * Check if penciled number in a row or col contains a unique number. Then change that tile
	 * 
	 * @param tile
	 * @return if change to tile was made
	 */
	private boolean uniquePencilCandidate(final ArrayList<Tile> tiles) {

		int[] penciled = new int[9]; // tallies number of penciled numbers in
										// row or col
		int[] dataToTile = new int[9]; // index of data gives the tile assigned
										// to it
		// tally penciled numbers
		for (int i = 0; i < tiles.size(); i++) {
			if (tiles.get(i).isBlank()) {
				for (int j = 0; j < tiles.get(i).getPencilNumbers().size(); j++) {
					// subtract 1 from numbers because array is 0-8, tiles are
					// 1-9
					penciled[tiles.get(i).getPencilNumbers().get(j) - 1]++;
					dataToTile[tiles.get(i).getPencilNumbers().get(j) - 1] = i;
				}
			}
		}
		boolean unique = false;
		int data = -1; // number to set tile data to
		// check if there were uniques
		for (int i = 0; i < penciled.length; i++) {
			if (penciled[i] == 1) {
				data = i;
				// add 1 because array is from 0-8, tiles are from 1-9
				solver.setNewTileData(tiles.get(dataToTile[data]), Board.IntToChar(data + 1));
				unique = true;
			}
		}
		return unique;
	}

}
